#-----------------------------------------------
#                 LICENSE
#-----------------------------------------------
# Copyright 2019 Novartis Institutes for BioMedical Research Inc.
# Licensed under the GNU General Public License, Version 3 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.r-project.org/Licenses/GPL-3
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


#'@title Estimated cell types across methods
#'
#'@description \code{plot_deconvolute} allows to compare methods across cell
#'types, where the different methods show a high level of agreement or
#'potentially generate diverging proportion estimates.
#'
#'@details Plots the estimated cell types generated by different deconvolution
#'methods/signature matrices across samples. Scaling is used to directly compare 
#'deconvolution outputs across methods.
#'
#'@param deconvoluted output object from function \code{deconvolute}.
#'
#'@param scale Boolean: indicate whether the coefficients should be 
#'transformed to standard scores (default: scale = TRUE).
#'
#'@param labels Boolean: indicate if x axis labels should be included
#'(default: labels = TRUE).
#'
#'@param markers Boolean: indicate if data points markers should be drawn
#'(default: markers = TRUE).
#'
#'@return line plot
#'
#'@import ggplot2
#'@importFrom dplyr mutate select bind_rows
#'@importFrom tidyr gather
#'@importFrom tibble as_tibble
#'@importFrom rlang .data
#'
#'@author Vincent Kuettel, Sabina Pfister
#'
#'@examples
#'# load demo PBMCS data
#'load_ABIS()
#'
#'# deconvolute
#'decon <- deconvolute(m = bulkRNAseq_ABIS, 
#'sigMatrix = sigMatrix_ABIS_S0)
#'
#'# plot deconvolute
#'plot_deconvolute(deconvoluted = decon)
#'
#'@export
plot_deconvolute <- function(deconvoluted = deconvoluted, scale = TRUE, labels = TRUE, markers=TRUE){

    dat <- deconvoluted$proportions
    met <- names(dat)

    # scale
    if(scale == TRUE)
        dat <- lapply(dat, scale)

    # format
    dat <- do.call(rbind, lapply(seq_along(dat), function(i){
        as_tibble(dat[[i]]) %>%
            mutate(model = names(dat)[[i]]) %>%
            mutate(sample = rownames(dat[[i]])) %>%
            gather("celltype", "coeff", -.data$sample, -.data$model) %>%
            as.data.frame()
    }))

    # plot
    g <- ggplot(data = dat, mapping = aes(x = .data$sample, y = .data$coeff, group = .data$model)) + geom_line(aes(color=.data$model))
    if (markers == TRUE)
        g <- g + geom_point(aes(color=.data$model), shape = 21, fill = "white", size=1)
    g <- g + facet_wrap(~celltype, scales="free_y", ncol = 3)

    if (labels == TRUE) {
        my_theme <- theme(
            axis.text.x = element_text(angle = 90, size = 5, hjust = 0.95, vjust = 0.2),
            axis.title = element_text(size = 12),
            plot.title = element_text(size = 12, face = 'bold', hjust = 0.5))

    } else {
        my_theme <- theme(
            axis.ticks.x = element_blank(),
            axis.text.x = element_blank(),
            axis.title = element_text(size = 12),
            plot.title = element_text(size = 12, face = 'bold', hjust = 0.5))
    }

    if (scale == TRUE){
        my_labs = labs(
            x = 'samples',
            y = 'scaled cell type proportions', 
            color = 'Models')
    } else {
        my_labs = labs(
            x = 'samples',
            y = 'absolute cell type proportions (%)', 
            color = 'Models')
    }

    return(g + my_theme + my_labs)
}
